﻿using System;
using System.Windows.Forms;

using Moe.ECamel.Common.Contracts;
using Moe.ECamel.Common.Entities;
using Moe.ECamel.Client.Controllers;
using Moe.ECamel.Client.WinForms.Common;
using Moe.ECamel.Client.WinForms.Forms;

namespace Moe.ECamel.Client.WinForms.Controls
{
	public partial class ItemListControl : ECamelUserControl
	{
		private ItemsController _controller;

		public ItemListControl()
		{
			InitializeComponent();
		}

		public void Initialize(ItemsController controller)
		{
			this._controller = controller;
			this.ListBindingSource.DataSource = _controller.List;
			this.SearchItemDetailsControl.Bind(_controller.SearchRequest.Template);
			ApplyPermissions();
			RefreshMenus();
		}

		private void ApplyPermissions()
		{
			RentItemToolStripButton.Available = RentItemToolStripMenuItem.Available = _controller.RentPermitted;
			AddToolStripMenuItem.Available = EntityAddToolStripMenuItem.Available = _controller.AddItemPermitted;
			EditToolStripMenuItem.Available = EntityEditToolStripMenuItem.Available = _controller.EditItemPermitted;
			AddCopyToolStripMenuItem.Available = _controller.AddInventoryPermitted;
			DeleteCopyToolStripMenuItem.Available = _controller.RemoveInventoryPermitted;
			TransferCopyToolStripMenuItem.Available = _controller.TransferInventoryPermitted;

			ContentToolStripDropDownButton.Available = HasAvailableSubItems(ContentToolStripDropDownButton);
			InventoryToolStripDropDownButton.Available = HasAvailableSubItems(InventoryToolStripDropDownButton);
		}

		private static bool HasAvailableSubItems(ToolStripDropDownItem dropDownItem)
		{
			foreach (ToolStripItem subItem in dropDownItem.DropDownItems)
				if (subItem.Available)
					return true;

			return false;
		}

		public void RefreshView()
		{
			// Refresh entity list:
			this._controller.RefreshList();
			// Refresh binding:
			this.ListBindingSource.CurrencyManager.Refresh();
			// Refresh menus:
			RefreshMenus();
		}
		private void RefreshMenus()
		{
			// Get current entity:
			var entity = GetCurrentItem();
			// Refresh available controls:
			bool hasValue = (entity != null);
			EntityViewToolStripButton.Enabled = EntityViewToolStripMenuItem.Enabled = hasValue;
			RentItemToolStripButton.Enabled = RentItemToolStripMenuItem.Enabled = hasValue;
			EditToolStripMenuItem.Enabled = EntityEditToolStripMenuItem.Enabled = hasValue;
			InventoryToolStripDropDownButton.Enabled = hasValue;
		}

		private void AddEntity()
		{
			using (var form = new ItemDetailsForm(_controller.NewCreateController()))
			{
				DialogResult result = form.ShowDialog();
				if (result == DialogResult.OK)
					RefreshView();
			}
		}
		private void ViewEntity()
		{
			// Get current entity:
			var entity = GetCurrentItem();
			if (entity != null)
			{
				using (var form = new ItemDetailsForm(_controller.NewViewController(entity)))
				{
					form.ShowDialog();
				}
			}
		}
		private void EditEntity()
		{
			// Get current entity:
			var entity = GetCurrentItem();
			if (entity != null)
			{
				using (var form = new ItemDetailsForm(_controller.NewEditController(entity)))
				{
					DialogResult result = form.ShowDialog();
					if (result == DialogResult.OK)
						RefreshView();
				}
			}
		}
		private void AddCopy()
		{
			// Get current entity:
			var entity = GetCurrentItem();
			if (entity != null)
			{
				_controller.AddCopy(entity);
				RefreshView();
			}
		}
		private void DeleteCopy()
		{
			// Get current entity:
			var entity = GetCurrentItem();
			if (entity != null)
			{
				_controller.DeleteCopy(entity);
				RefreshView();
			}
		}
		private void TransferCopy()
		{
			// Get current entity:
			var entity = GetCurrentItem();
			if (entity != null)
			{
				TransferCopyResponse response = _controller.TransferCopy(entity);
				if (response.IsSuccessful)
				{
					ECamelHelper.ShowMessage(MessageIds.InventoryTrasferSucceeded, response.ItemTitle, response.ItemCatalogNumber, response.SourceLibraryName, response.TargetLibraryName);
					RefreshView();
				}
				else
					ECamelHelper.ShowMessage(MessageIds.InventoryTrasferFailed);
			}
		}
		private void RentItem()
		{
			// Get current entity:
			var entity = GetCurrentItem();
			if (entity == null)
				return;

			// Check if customer has an active debt:
			var customer = _controller.GetCustomer();
			if (customer.TotalDebt != 0)
			{
				// If customer has a debt, ask user if they want to continue with rental:
				var result = ECamelHelper.ShowMessage(MessageIds.RentalCustomerHasDebt, customer.TotalDebt);
				if (result == DialogResult.No)
					return;
			}

			var response = _controller.RentItem(entity);
			if (response.Error == null)
			{
				ECamelHelper.ShowMessage(MessageIds.RentalSuccessful, response.Rental.ExpectedReturnDate.ToShortDateString());
				RefreshView();
			}
			else if (response.Error.MessageId == MessageIds.RentalInvalidNoAvailableInventory)
			{
				using (var dialog = new RentalAdvancedForm(_controller, entity))
				{
					var result = dialog.ShowDialog();
					if (result == DialogResult.OK)
						RefreshView();
				}
			}
			else
				ECamelHelper.ShowMessage(response.Error);
		}

		private Item GetCurrentItem()
		{
			var selectedItem = ListBindingSource.Current;
			return selectedItem == null ? null : ((SearchItemResult) selectedItem).Item;
		}

		private void EntityViewToolStripButton_Click(object sender, EventArgs e)
		{
			ViewEntity();
		}
		private void RentItemToolStripButton_Click(object sender, EventArgs e)
		{
			RentItem();
		}
		private void AddToolStripMenuItem_Click(object sender, EventArgs e)
		{
			AddEntity();
		}
		private void EditToolStripMenuItem_Click(object sender, EventArgs e)
		{
			EditEntity();
		}
		private void AddCopyToolStripMenuItem_Click(object sender, EventArgs e)
		{
			AddCopy();
		}
		private void DeleteCopyToolStripMenuItem_Click(object sender, EventArgs e)
		{
			DeleteCopy();
		}
		private void TransferCopyToolStripMenuItem_Click(object sender, EventArgs e)
		{
			TransferCopy();
		}

		private void EntityViewToolStripMenuItem_Click(object sender, EventArgs e)
		{
			ViewEntity();
		}
		private void RentItemToolStripMenuItem_Click(object sender, EventArgs e)
		{
			RentItem();
		}
		private void EntityAddToolStripMenuItem_Click(object sender, EventArgs e)
		{
			AddEntity();
		}
		private void EntityEditToolStripMenuItem_Click(object sender, EventArgs e)
		{
			EditEntity();
		}

		private void ListDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			ViewEntity();
		}
		private void SearchButton_Click(object sender, EventArgs e)
		{
			RefreshView();
		}
	}
}